package com.ttc.ssm.controller.home;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttc.ssm.controller.common;
import com.ttc.ssm.po.*;
import com.ttc.ssm.service.admin.CompanyService;
import com.ttc.ssm.service.home.HomeAdService;
import com.ttc.ssm.service.home.HomeCommonService;
import com.ttc.ssm.service.home.HomeCompanyService;
import com.ttc.ssm.service.home.HomeCustomerService;
import com.ttc.ssm.utils.MailUtil;
import com.ttc.ssm.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jiarui on 2016/8/3.
 */
@Controller
public class HomeIndexController {

    @Autowired
    HomeCommonService homeCommonService;

    @Autowired
    HomeCustomerService homeCustomerService;

    @Autowired
    HomeCompanyService homeCompanyService;

    @Autowired
    CompanyService companyService;

    @Autowired
    HomeAdService homeAdService;

    @RequestMapping("/index")
    public String index(Model model,HttpSession session) throws Exception {
        String type = (String) session.getAttribute("type");
        if(type!= null && type.equals("0")){
            int customer_id = (Integer) session.getAttribute("customer_id");
            int noReadCountInvite = homeCustomerService.countRowsNoReadCustomer(customer_id);
            List<InviteActivity> inviteActivities = homeCustomerService.selectActivityCustomer(customer_id);
            model.addAttribute("inviteActivities",inviteActivities);
            int deliveryCount = homeCustomerService.countRowsNoReadCustomerDelivery(customer_id);
            List<DeliveryActivity> deliveryActivities = homeCustomerService.selectDeliveryActivityCustomer(customer_id);
            model.addAttribute("deliveryActivities",deliveryActivities);
            model.addAttribute("totalCount",noReadCountInvite+deliveryCount);
        }
        if(type != null && type.equals("1")){
            int company_id = (Integer) session.getAttribute("company_id");
            int noReadCountInvite = homeCompanyService.countRowsNoReadCompany(company_id);
            List<InviteActivity> inviteActivities = homeCompanyService.selectActivityCompany(company_id);
            int deliveryCount = homeCompanyService.countRowsNoReadCompanyDelivery(company_id);
            List<DeliveryActivity> deliveryActivities = homeCompanyService.selectDeliveryActivityCompany(company_id);
            model.addAttribute("inviteActivities", inviteActivities);
            model.addAttribute("deliveryActivities", deliveryActivities);
            model.addAttribute("totalCount",  noReadCountInvite+deliveryCount);
        }
        List<Ad> adList = homeAdService.selectAd();
        model.addAttribute("adList", adList);
        return "home/index/index";
    }

    @RequestMapping("/getCityList")
    public @ResponseBody List<City> getCityList(Integer zone_id) throws Exception {
        return homeCommonService.getCityByZoneId(zone_id);
    }

    @RequestMapping("/getAllCity")
    public @ResponseBody List<City> getAllCity() throws Exception {
        return homeCommonService.getAllCity();
    }

    @RequestMapping("/checkExist")
    public @ResponseBody String checkExist(String e_mail) throws Exception {
        boolean result = true;
        Company company = homeCustomerService.getCompanyByEmail(e_mail);
        if(company!=null)
            result = false;
        Map<String, Boolean> map = new HashMap();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        resultString = mapper.writeValueAsString(map);
        return resultString;
    }

    @RequestMapping("/checkExistCustomerEmail")
    public @ResponseBody String checkExistCustomerEmail(String email) throws Exception {
        boolean result = true;
        Map where = new HashMap();
        where.put("email",email);
        where.put("telephone",null);
        if(homeCustomerService.checkExist(where) >= 1){
            result = false;
        }
        Map<String, Boolean> map = new HashMap();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        resultString = mapper.writeValueAsString(map);
        return resultString;
    }

    @RequestMapping("/checkExistCustomerPhone")
    public @ResponseBody String checkExistCustomerPhone(String telephone) throws Exception {
        boolean result = true;
        Map where = new HashMap();
        where.put("email",null);
        where.put("telephone",telephone);
        if(homeCustomerService.checkExist(where) >= 1){
            result = false;
        }
        Map<String, Boolean> map = new HashMap();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        resultString = mapper.writeValueAsString(map);
        return resultString;
    }

    @RequestMapping("/checkOldPasswordCompany")
    public @ResponseBody String checkOldPasswordCompany(String old_password, HttpSession session) throws Exception {
        boolean result = true;
        Integer company_id = (Integer) session.getAttribute("company_id");
        Company tmp = companyService.selectCompanyById(company_id);
        if(tmp != null) {
            if (!tmp.getPassword().equals(common.SHA1(tmp.getSalt() + common.SHA1(tmp.getSalt() + common.SHA1(old_password))))) {
                result = false;
            }
        }
        Map<String, Boolean> map = new HashMap();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        resultString = mapper.writeValueAsString(map);
        return resultString;
    }

    @RequestMapping("/checkOldPasswordCustomer")
    public @ResponseBody String checkOldPasswordCustomer(String old_password, HttpSession session) throws Exception {
        boolean result = true;
        Integer customer_id = (Integer) session.getAttribute("customer_id");
        Customer tmp = homeCustomerService.getCustomerById(customer_id);
        if(tmp != null) {
            if (!tmp.getPassword().equals(common.SHA1(tmp.getSalt() + common.SHA1(tmp.getSalt() + common.SHA1(old_password))))) {
                result = false;
            }
        }
        Map<String, Boolean> map = new HashMap();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        resultString = mapper.writeValueAsString(map);
        return resultString;
    }


    @RequestMapping("secrecy")
    public String secrecy() throws Exception
    {
        return "home/index/secrecy";
    }

    @RequestMapping("about")
    public String about() throws Exception
    {
        return "home/index/about";
    }

    @RequestMapping("law")
    public String law() throws Exception
    {
        return "home/index/law";
    }

    @RequestMapping("contact")
    public String contact() throws Exception
    {
        return "home/index/contact";
    }


    @RequestMapping("sendEmail")
    public String sendEmail(Feedback feedback, Model model) throws Exception
    {
        if (TextUtils.isEmpty(feedback.getEmail()) || TextUtils.isEmpty(feedback.getPhone()) || TextUtils.isEmpty(feedback.getCompany())
                || TextUtils.isEmpty(feedback.getName()) || TextUtils.isEmpty(feedback.getMessage())) {
            model.addAttribute("warn",1);
            return "forward:contact.action";
        }
        StringBuilder builder = new StringBuilder();
        builder.append("姓名：").append(feedback.getName());
        if (!feedback.getCompany().equals("-1")) {
            builder.append("\n公司名称：").append(feedback.getCompany());
        }
        builder.append("\n邮箱：").append(feedback.getEmail());
        builder.append("\n联系电话：").append(feedback.getPhone());
        builder.append("\n建议或反馈：").append(feedback.getMessage());
        String message = builder.toString();
        boolean flag = new MailUtil().sendEmail("582962019@qq.com","反馈",message);
        if (flag) {
            model.addAttribute("success",1);
            return "forward:contact.action";
        }else {
            model.addAttribute("error",1);
            return "forward:contact.action";
        }
    }
}
